package com.siruier.boss.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Matrix
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

object BitmapUtil {
    fun changeBitmapSize(bitmap: Bitmap?, newWidth: Int, newHeight: Int): Bitmap? {
        if (bitmap == null) return null
        var bitmap = bitmap
        val width = bitmap.width
        val height = bitmap.height
        //计算压缩的比率
        val scaleWidth = newWidth.toFloat() / width
        val scaleHeight = newHeight.toFloat() / height
        //获取想要缩放的matrix
        val matrix = Matrix()
        matrix.postScale(scaleWidth, scaleHeight)
        //获取新的bitmap
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true)
        bitmap.width
        bitmap.height
        return bitmap
    }

    fun saveBitmapFile(context: Context, bitmap: Bitmap): File {
        val file = File(context.cacheDir, "temp.png")
        try {
            val bos = BufferedOutputStream(FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush()
            bos.close()
        } catch (e: IOException) {
        }
        return file
    }
}